package com.witmore.skyline.web.controller.api;

import com.alibaba.fastjson.JSONObject;
import com.witmore.skyline.web.controller.enums.WitmoreErrorCode;
import com.witmore.skyline.web.controller.vo.result.ResponseResult;
import com.witmore.skyline.web.service.messagehandler.MessageProcessor;
import com.witmore.skyline.web.service.messagehandler.MessageType;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * openApi:接收云机械推送接口
 * Author: 豆子高
 * Date: 2025/4/16 11:52
 */
@Slf4j
@RestController
@RequestMapping("witmore/open/device/message/")
public class DeviceApiClientController {

    @Autowired
    private MessageProcessor messageProcessor;

    /**
     * 接收云机械消息推送接口
     *
     * @param param 推送消息体
     */
    @PostMapping("receive")
    public ResponseResult<Void> receive(@RequestBody CloudmMessageParam param) {
        if (null == param) {
            return ResponseResult.fail(WitmoreErrorCode.PARAM_ERROR.getCode(), "请求参数不能为空");
        }
        if (ObjectUtils.isEmpty(param.getMessageType())) {
            return ResponseResult.fail(WitmoreErrorCode.PARAM_ERROR.getCode(), "消息类型不能为空");
        }
        // 校验枚举
        try {
            MessageType.valueOf(param.getMessageType());
        } catch (Exception e) {
            return ResponseResult.fail(WitmoreErrorCode.PARAM_ERROR.getCode(), "消息类型错误");
        }
        if (null == param.getSn()) {
            return ResponseResult.fail(WitmoreErrorCode.PARAM_ERROR.getCode(), "设备sn不能为空");
        }
        if (ObjectUtils.isEmpty(param.getContent())) {
            return ResponseResult.fail(WitmoreErrorCode.PARAM_ERROR.getCode(), "消息内容不能为空");
        }
        log.info("接收云机械推送消息: {}", JSONObject.toJSONString(param));
        messageProcessor.processMessage(param);
        return ResponseResult.success();
    }
}
